<?php
/**
 * Created by PhpStorm.
 * User: yuanxuncheng
 * Date: 2016-12-19
 * Time: 0:02
 */

namespace app\library;

use app\api\model\dao\IntegralLog;
use app\api\model\dao\UserCurrency;
use app\library\Redis;
use think\Cache;
use think\Log;


class Common
{
    /**
     * @desc 计算签名
     * @param $data
     * @return string
     */
    public static function computeSign($data)
    {
        $time = $data['time'];
        unset($data['time']);    // 删除这两个参数再来进行排序     
        unset($data['sign']);    // 删除这两个参数再来进行排序
        ksort($data);
        $str = implode('', $data);
        $str = $str . $time . CommonConfig::API_SECRET_KEY;
        return md5($str);
    }

    /**
     * @desc 生成token
     * @return string
     */
    public static function getToken()
    {
        return md5(time() . mt_rand(1, 999999999));
    }

    /**
     * @desc 生成sessionid
     * @param $userid
     * @param $identifier
     * @param $credential
     * @return string
     */
    public static function gererateSession($userid, $identifier, $credential)
    {
        return md5($userid . $identifier . $credential);
    }

    /**
     * @desc 加密密码
     * @param $password
     * @return string
     */
    public static function encodePassword($password)
    {
        return md5($password);
    }

    /**
     * @desc 生成验证码
     * @param $phone
     * @param int $length
     * @param int $numeric
     * @return bool|string
     */
    public static function createVerificationCode($phone, $length = 6, $numeric = 0)
    {
        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
        if ($numeric) {
            $hash = sprintf('%0' . $length . 'd', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for ($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        $ret = Cache::set('sms:' . $phone, $hash, Flag::SMS_EXPIRE_TIME);
        if (false === $ret) {
            Log::alert('Cache verification failed');
            return false;
        }
        return $hash;
    }

    /**
     * @desc 验证手机号是否正确
     * @param int $mobile
     */
    public static function isMobile($mobile)
    {
        if (!is_numeric($mobile)) {
            return false;
        }
        return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
    }

    /**
     * @param $xml
     * @return mixed
     * @desc xml转换成array
     */
    public function xmlToArray($xml)
    {
        //将XML转为array
        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }

    /**
     * 无限级分类
     * @param array $data //数据库里获取的结果集
     * @param int $parent_id
     * @param int $count //第几级分类
     * return array $categoryTreeList
     */
    public static function getCategoryTree(&$data, $parent_id = 0, $count = 1, &$categoryTreeList)
    {
        foreach ($data as $key => $value) {
            if (isset($value['parent_id']) && isset($value['cat_id'])) {
                if ($value['parent_id'] == $parent_id) {
                    $value['level'] = $count;
                    $categoryTreeList[] = $value;
                    unset($data[$key]);
                    self::getCategoryTree($data, $value['cat_id'], $count + 1, $categoryTreeList);
                }
            }
        }
        return $categoryTreeList;
    }


    /**
     * 对文本进行分词
     *
     * @param $content - 需要切分的文本
     * @param null $num - 获取词频top num个词
     * @return mixed
     */
    public static function scws($content, $num = null)
    {
        $pscws = new \think\util\Pscws('utf8');
        $pscws->set_charset('utf-8');
        $pscws->set_dict(DICT_CONF_PATH . 'dict.utf8.xdb');
        $pscws->set_rule(DICT_CONF_PATH . 'rules.utf8.ini');
        $pscws->set_ignore(true);
        $pscws->send_text($content);
        $words = $pscws->get_tops($num);
        $pscws->close();
        $tags = array();
        foreach ($words as $val) {
            $tags[] = $val['word'];
        }
        return $tags;
    }

    public static function encryptString($str)
    {
        $prefix = '#abcdefg#';
        $suffix = '#higklmn#';
        return md5($prefix . $str . $suffix);
    }

    public static function caleDate($timestamp)
    {
        $now = time();
        $subtraction = $now - $timestamp;
        if ($subtraction < 60) {
            return $subtraction . '秒前';
        } else if ($subtraction < 3600) {
            return floor($subtraction / 60) . '分钟前';
        } else if ($subtraction < 86400) {
            return floor($subtraction / 3600) . '小时前';
        } else if ($subtraction < 2592000) {
            return floor($subtraction / 86400) . '天前';
        } else {
            return floor($subtraction / 2592000) . '月前';
        }
    }

    public static function modelToArray($param)
    {
        if (empty($param)) {
            return $param;
        }
        if ($param instanceof \think\Model) {
            return $param->getData();
        }

        if (is_array($param)) {
            $data = [];
            foreach ($param as $val) {
                //var_dump($val->getData());
                array_push($data, $val->getData());
            }
            return $data;
        }

        return [];
    }

    /**
     * 根据漫豆数获取等级
     *
     * @param $integral
     * @return int
     */
    public static function conversionLevel($integral)
    {
        $leve_base = 30;
        $diff = 70;
        $level = 0;

        if ($integral <= $leve_base) {
            return $level;
        }

        $level++;

        while ($integral > ($leve_base + $diff)) {
            $leve_base = $leve_base + $diff;
            $diff += 10;
            $level++;
        }

        return $level;
    }

    /**
     * 增加漫豆积分
     *
     * @param $userid
     * @param $source
     */
    public static function addIntegral($userid, $source)
    {
        $obj = new IntegralLog();
        $date = 0;
        if (!in_array($source, ['task_account', 'task_note', 'task_reply_note'])) {
            $date = date('Ymd');
        }
        $cnt = $obj->getCountByUseridAndSourceAndDate($userid, $source, $date);
        if ($cnt >= Flag::$integral_rule[$source]['num']) {
            return;
        }
        $input = [
            'userid' => $userid,
            'source' => $source,
            'date' => date('Ymd'),
            'create_time' => time(),
        ];
        $ret = $obj->add($input);
        if (false === $ret) {
            Log::error(__METHOD__ . ' insert integral_log fail. [input:' . json_encode($input) . ']');
        }
        $objUserCurrency = new UserCurrency();
        $ret = $objUserCurrency->changeCurrency($userid, Flag::CURENCY_TYPE_INTEGRAL, Flag::$integral_rule[$source]['once']);
        if (false === $ret) {
            Log::error(__METHOD__ . ' add currency(integral) fail. [userid:' . $userid . '][source:' . $source . ']');
        }
        return;
    }
}